import axios from 'axios';
import { cloneDeep } from 'lodash';
import { ElMessage } from 'element-plus';
import { parse, compile } from 'path-to-regexp';
import {useCache} from "@/hooks/web/useCache";
import { useAppStore } from "@/store/modules/app";
import { useTagsViewStore } from '@/store/modules/tagsView'
import Vrouter from "@/router"

const tagsViewStore = useTagsViewStore()
const {wsCache}=useCache();
const appStore = useAppStore();
const { CancelToken } = axios;
//不进行跳转的白名单
const prefixWhiteList = ['service/focus-service/device'];
(window as any).cancelRequest = new Map();
function getAuthorization(){
	let requestToken=wsCache.get(appStore.getUserToken);	
	requestToken=requestToken?"bearer "+requestToken:requestToken;
	return requestToken;
  }
export default function request(options: any) {
	const { data } = options;
	let { url } = options;
	const cloneData = cloneDeep(data);

	try {
		let domain = '';
		const urlMatch = url.match(/[a-zA-z]+:\/\/[^/]*/);
		if (urlMatch) {
			[domain] = urlMatch;
			url = url.slice(domain.length);
		}

		const match = parse(url);
		url = compile(url)(data);

		for (const item of match) {
			if (item instanceof Object && item.name in cloneData) {
				delete cloneData[item.name];
			}
		}
		url = domain + url;
	} catch (e: any) {
		ElMessage.error(e.message);
	}
	const param = new URLSearchParams();
	for (const k in data) {
		if(data[k]==null||data[k]==undefined) data[k]="";
		param.append(k, data[k]);
	}
	options.headers = { 'Content-Type': 'application/x-www-form-urlencoded',authorization:getAuthorization() };
	if (options.method == 'GET'){		
		options.params = param;
	}else if(options.method == "FILE"){
		options.method="POST"
		options.headers = { 'Content-Type': 'multipart/form-data',authorization:getAuthorization() };		
	}
	else if(options.method=="DOWNLOAD"){
		options.method="GET"
		options.responseType='blob'
		options.params = param;
	}
	else {
		options.data = param;
	}	

	options.url = url;
	options.cancelToken = new CancelToken((cancel) => {
		(window as any).cancelRequest.set(Symbol(Date.now()), {
			pathname: window.location.pathname,
			cancel,
		});
	});
	return axios(options)
		.then((response) => {			
			const { statusText, status, data } = response;
			console.log(options)
			if(options.responseType=="blob"){
				const blob=new Blob([data],{type:"application/vnd.ms-excel"});
				const a=document.createElement('a');
				const href=window.URL.createObjectURL(blob);
				a.href=href;
				let filename=param["filename"]
				if(!param["filename"]){
					filename=response.headers["content-disposition"].substring(response.headers["content-disposition"].indexOf("filename"));
					filename=filename.substring(filename.indexOf("=")+1,filename.indexOf(';')>=0?filename.indexOf(';'):filename.length);
					filename=decodeURIComponent(filename);
				}
				if(!filename)filename="下载文件"
				a.download=filename;
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);
				window.URL.revokeObjectURL(href);
				return;
			}
			return Promise.resolve({
				success: true,
				statusMessage: statusText,
				statusCode: status,
				data:data,
			});
		})
		.catch((error) => {
			const { response } = error;
			let msg;
			let statusCode;
			if (response && response instanceof Object) {
				const { data, statusText } = response;
				let prefixIndex =0;
				console.log(options.url)
				for(prefixIndex=0;prefixIndex<prefixWhiteList.length;prefixIndex++){
					if(options.url.startsWith(prefixWhiteList[prefixIndex]))
						break;
				}
				if(response.status == 401&&prefixIndex==prefixWhiteList.length) {
					ElMessage.error('登录失效,请重新登录');
					setTimeout(() => {
						wsCache.set(appStore.getUserInfo, null);
						wsCache.set(appStore.getUserToken, null);
						tagsViewStore.delAllViews()
						Vrouter.replace({path:'/login'});
					}, 300);
				}
				statusCode = response.status;
				msg = data.message || statusText;
				
			} else {
				statusCode = 600;
				msg = error.message || '请求失败';
			}
			ElMessage.error(msg);
			/* eslint-disable */
			return Promise.reject({
				success: false,
				statusCode,
				statusMessage: msg,
			});
		});
}

